<?php
/**
 * Created by PhpStorm.
 * User: tjjs
 * Date: 17-5-24
 * Time: 上午11:21
 */

namespace ActionsHttp;

use Data\Food_DAO;
use Data\Order_for_foods;
use Data\Order_for_foods_DAO;
use Data\Order_form;
use Data\Order_form_DAO;
use Data\Restaurant_certification_DAO;
use Utils\Socket_to_restaurant;

class ConsumerOrderNew extends BaseActionHttp
{
    public function doAction() {
        parent::doAction();
        // 顾客id
        $consumer_id = $_SESSION[CONSUMER_ID];
        $consumer_id = 1;
        // 餐馆id
        $restaurant_id = (int)$this->data[RESTAURANT_ID];
        // 商铺认证信息
        $restaurant_certification_record = Restaurant_certification_DAO::getRecord($restaurant_id);
        // 商铺认证是否通过
        $permission_status = $restaurant_certification_record->getPERMMISION_STATUS();
        if ($permission_status != 1) {
            return $this->SendErrMsg("错误，该商铺未认证通过");
        }

        // 桌号
        $table_number = $this->data[TABLE_NUM];
        // 是否外带
        $is_take_out  = (int)$this->data[IS_TAKE_OUT];
        // 详细订单
        $order_for_food = $this->data[ORDER_FOR_FOOD];
        // 生成订单
        $order_form_record = new Order_form(array());
        if (!array_key_exists($is_take_out,array(STATE_YES,STATE_NO))) {
            return $this->SendErrMsg("参数错误，请选择外带或是在餐厅内食用");
        }
        // 用餐人数
        $consumer_count = $this->data[CONSUMER_COUNT];
        $order_for_foods_list = array();
        $total_price = 0;
        $lunchbox_amounts = 0;
        $lunchbox_price = 0;

        foreach ($order_for_food as $food_id=>$food_count) {
            // 商品记录
            $food_record = Food_DAO::getRecordByIdResId($food_id,$restaurant_id);
            if (!$food_record) {
                return $this->SendErrMsg("参数错误，有商品不存在");
            }
            // 商品存在
            // 商品是否限量
            $food_is_limit = $food_record->getIS_LIMIT();
            if ($food_is_limit == STATE_YES) {
                // 商品限量
                // 商品剩余量
                $stock_left =  $food_record->getSTOCK_LEFT();
                if ($food_count>$stock_left) {
                    return $this->SendErrMsg("参数错误，有商品库存不足");
                }
            }

            // 商品单价
            $food_price = $food_record->getFOOD_PRICE();
            // 商品名称
            $food_name = $food_record->getFOOD_NAME();
            // 商品所需餐盒数量
            $food_lunchbox_amounts = $food_record->getLUNCHBOX_AMOUNTS();
            // 商品餐盒价格
            $food_lunchbox_price = $food_record->getLUNCHBOX_PRICE();
            if ($is_take_out == STATE_YES) {
                // 订单总餐盒数量
                $lunchbox_amounts += $food_count*($food_lunchbox_amounts);
                $lunchbox_price += $food_count*($food_lunchbox_price);
            }

            // 订单总价
            $total_price += $food_price*$food_count;

            $order_for_foods_list[$food_id] = array($food_count,$food_price,$food_name,$food_lunchbox_amounts,$food_lunchbox_price);
        }
        if ($is_take_out == STATE_YES) {
            $total_price += $lunchbox_price;
        }

        try {
            // 事务 开始
            $dbMain = \GatewayWorker\Lib\Db::instance('main');
            $dbMain->beginTrans();

            $order_num = ConsumerOrderNew::getOrderNum($consumer_id);
            $order_form_record->setORDER_NUM($order_num);
            $order_form_record->setTABLE_NUM($table_number);
            $order_form_record->setRESTAURANT_ID($restaurant_id);
            $order_form_record->setCREATED_BY($consumer_id);
            $order_form_record->setCONSUMER_COUNT($consumer_count);
            $order_form_record->setTOTAL_PRICE($total_price);
            $order_form_record->setTOTAL_PRICE_LEFT($total_price);
            $order_form_record->setIS_TAKE_OUT($is_take_out);
            $order_form_record->setLUNCHBOX_TOTAL_AMOUNTS($lunchbox_amounts);
            $order_form_record->setLUNCHBOX_TOTAL_AMOUNTS_LEFT($lunchbox_amounts);
            $order_form_record->setLUNCHBOX_TOTAL_PRICE($lunchbox_price);
            $order_form_record->setLUNCHBOX_TOTAL_PRICE_LEFT($lunchbox_price);
            $order_form_record->setDATE(date("Y-m-d"));

            // **********************
            $order_form_record->setPAY_STATUS(PAY_STATUS_YES);
            $order_form_record->setPAY_WAY(PAY_WAY_ZFB);
            $order_form_record->setPAY_TIME(time());
            // ***********************
            $order_form_id = Order_form_DAO::insert($order_form_record);

            foreach ($order_for_foods_list as $food_id=>$food_info) {
                $order_for_foods_record = new Order_for_foods(array());
                $order_for_foods_record->setORDER_FORM_ID($order_form_id);
                $order_for_foods_record->setRESTAURANT_ID($restaurant_id);
                $order_for_foods_record->setFOOD_ID($food_id);
                $order_for_foods_record->setFOOD_COUNT($food_info[0]);
                $order_for_foods_record->setFOOD_COUNT_LEFT($food_info[0]);
                $order_for_foods_record->setFOOD_PRICE($food_info[1]);
                $order_for_foods_record->setFOOD_NAME($food_info[2]);
                $order_for_foods_record->setLUNCHBOX_AMOUNTS($food_info[3]);
                $order_for_foods_record->setLUNCHBOX_PRICE($food_info[4]);
                // ***********************
                $order_for_foods_record->setIS_PAY(STATE_YES);
                //*************************
                $order_for_foods_record->setDATE(date("Y-m-d"));
                $order_for_foods_record->setCREATED_BY($consumer_id);
                Order_for_foods_DAO::insert($order_for_foods_record);
            }
            //事务 提交
            $dbMain->commitTrans();

        } catch (\Exception $ex) {
            //出现异常,回滚
            echo "预料外错误~~~~\n";
            echo $ex->getMessage()."\n";
            echo $ex->getTraceAsString()." ~~~ traceString\n";
            echo $ex->getCode()."  ~~code  \n";
            echo $ex->getFile()." ~~ file \n";
            echo $ex->getLine()." ~~ line \n";
            echo $ex->getPrevious() ." ~~ previous \n";
            $dbMain->rollBackTrans();
            // 预料外的错误
            return $this->SendErrMsg("预料外的错误~!");
        }

        // *******************付款*****************

        // socket推送

        $data = array(
            "ActionType" => "event_restaurant_new_order",
            "DataDictionary" => array(
                "ORDER_FORM_ID"=>$order_form_id
            )
        );
        new Socket_to_restaurant(json_encode($data));
        // 返回数据
        $this->setValue(ORDER_FORM_ID,$order_form_id);
        $this->setValue(ORDER_NUM,$order_num);
        $this->ResponseDataToCurrentClient();
    }

    public function getOrderNum($consumer_id){
        // 生成订单号
        // 时间戳
        $time = time();
        $order_num = $time.$consumer_id;
        return $order_num;
    }

}